<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/3/19
 * Time: 17:02
 */

namespace app\common\controller;

use Exception;
use think\Controller;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

class Backend extends AuthBase
{
    /**
     * [通用添加、修改专用] 模型名称，格式：模块名/模型名
     * @var \think\Model
     */
    protected $hsModel = null;

    /**
     * [通用添加、修改专用] 表名(不含表前缀)
     * @var \think\Model
     */
    protected $hsTable = null;

    /**
     * 是否开启Validate验证
     */
    protected $modelValidate = false;

    /**
     * 是否开启模型场景验证
     */
    protected $modelSceneValidate = false;

    /**
     * 前台提交过来,需要排除的字段数据
     */
    protected $excludeFields = "";

    /**
     * 实例化模型类($hsModel)
     */
    protected function model()
    {

        if (!$this->hsModel) {
            $this->error('hsModel属性未定义');
        }

        if (defined('IS_PLUGINS')) {
            if (strpos($this->hsModel, '\\') === false) {
                $this->hsModel = 'plugins\\' . $this->request->param('_p') . '\\model\\' . $this->hsModel;
            }

            return (new $this->hsModel);
        } else {
            if (strpos($this->hsModel, '/') === false) {
                $this->hsModel = $this->request->module() . '/' . $this->hsModel;
            }

            return model($this->hsModel);
        }
    }

    /**
     * 排除前台提交过来的字段
     * @param $params
     * @return array
     */
    protected function preExcludeFields($params)
    {
        if (is_array($this->excludeFields)) {
            foreach ($this->excludeFields as $field) {
                if (key_exists($field, $params)) {
                    unset($params[$field]);
                }
            }
        } else {
            if (key_exists($this->excludeFields, $params)) {
                unset($params[$this->excludeFields]);
            }
        }
        return $params;
    }

    /*
     * 查询根据$group来筛选
     */
    public function statistics($group)
    {
        // 获取 bug总数
        $bugSum = Db::name('projectBug')->where('deleted','null')->group($group)->column('count(status)', $group);
        // 未关闭bug
        $notBug = Db::name('projectBug')->where('deleted','null')->where('status', '<>', 3)->group($group)->column("count(status),$group", $group);
        // 获取 需求总数
        $needSum = Db::name('projectNeed')->where('deleted','null')->group($group)->column('count(status)', $group);
        // 获取 待开发需求
        $dealNeed = Db::name('projectNeed')->where('deleted','null')->group($group)->where('status', 1)->column('count(status)', $group);
        // 获取 开发中需求
        $exploitNeed = Db::name('projectNeed')->where('deleted','null')->group($group)->where('status', 2)->column('count(status)', $group);
        // 获取 待测试需求
        $testNeed = Db::name('projectNeed')->where('deleted','null')->group($group)->where('status', 3)->column('count(status)', $group);
        // 获取 版本总数
        $versions_sum = Db::name('versions')->where('deleted','null')->group('product_id')->column('count(product_id)', 'product_id');
        // 获取 最新版本
        $new_versions = Db::name('versions')->where('deleted','null')->order('ctime','desc')->group('product_id')->column('name', 'product_id');
        return [$bugSum, $notBug, $needSum, $dealNeed, $exploitNeed, $testNeed, $versions_sum,$new_versions];
    }

    /**
     * 查询
     */
    public function query($id)
    {
        if ( !isset($id) ) {
            return json(['code' => 0, 'msg' => '缺少必要参数']);
        }
        if ( $this->request->isPost() ) {
            $data = $this->model()->where('id',$id)->find();
            $data['time'] = isset($data['etime']) ? strtotime($data['etime']) : strtotime($data['ptime']);
            return json(['code' => 0, 'msg' => 'ok', 'data' => $data]);
        }
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            if ($this->hsModel) {
                $model = $this->model();
            } else if ($this->hsTable) {
                $model = db($this->hsTable);
            } else {
                return $this->error('当前控制器缺少属性（hsModel、hsTable至少定义一个）');
            }

            $params = $this->request->post();

            if ($params) {
                $params = $this->preExcludeFields($params);
                $params['creator'] = USER_ID;
                $result = false;
                Db::startTrans();
                try {
                    // 是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $model->validateFailException(true)->validate($validate);
                    }

                    $result = $model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result) {
                    return json(['code' => 0, 'msg' => '增加成功']);
                }
                return json(['code' => 1, 'msg' => '增加失败']);
            }
            return json(['code' => 1, 'msg' => '参数有误，请重新确认参数！']);
        }
    }

    /**
     * 编辑
     */
    public function edit($ids = "")
    {
        if ($this->request->isPost()) {
            if ($this->hsModel) {
                $model = $this->model();
            } else if ($this->hsTable) {
                $model = db($this->hsTable);
            } else {
                return $this->error('当前控制器缺少属性（hisiModel、hisiTable至少定义一个）');
            }

            $data = $model->get($ids);
            if (!$data) {
                return json(['code' => 1, 'msg' => '编辑数据不存在']);
            }

            $params = $this->request->post();
            //$params['creator'] = USER_ID;
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    // 是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $data->validateFailException(true)->validate($validate);
                    }
                    $result = $data->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }

                return json(['code' => 0, 'msg' => '编辑成功']);
            }
            return json(['code' => 1, 'msg' => '参数有误，请重新确认参数！']);
        }
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($this->request->isPost()) {
            if ($ids) {
                if ($this->hsModel) {
                    $model = $this->model();
                } else if ($this->hsTable) {
                    $model = db($this->hsTable);
                } else {
                    return $this->error('当前控制器缺少属性（hisiModel、hisiTable至少定义一个）');
                }

                $pk = $model->getPk();
                $list = $model->where($pk, 'in', $ids)->select();
                $count = 0;
                Db::startTrans();
                try {
                    foreach ($list as $k => $v) {
                        $count += $v->delete();
                    }
                    Db::commit();
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($count > 0) {
                    return json(['code' => 0, 'msg' => '删除成功']);
                }
                return json(['code' => 1, 'msg' => '删除失败']);
            }
            return json(['code' => 1, 'msg' => '参数有误，请重新确认参数！']);
        }
    }

    /**
     * 分组功能
     */
    public function get_group($arr,$field = [])
    {
        if(count($arr) >= 2){
            $tmparr = array();
            $arr1 = array_shift($arr);
            $arr2 = array_shift($arr);
            foreach($arr1 as $k1 => $v1){
                foreach($arr2 as $k2 => $v2){
                    $tmparr[] = [$field[0] => $v1, $field[1] => $v2];
                }
            }
            array_unshift($arr, $tmparr);
            $arr = $this->get_group($arr);
        }else{
            return $arr;
        }
        return $arr;
    }

}